
package logic.forms;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import logic.beans.Food;
import logic.beans.FoodComponent;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import controller.SEISaudeDefaultFacade;

public class FoodForm extends ElementForm<Food> {
	private static final long serialVersionUID = 1L;
	
	@Override
	public ActionErrors validate(ActionMapping mapping,HttpServletRequest request) {
		ActionErrors errors = new ActionErrors();
		
		if (getElement().getName() == null || getElement().getName().isEmpty()) {
			errors.add("name",new ActionMessage("food.register.error.name.empty"));
		}
		
		return errors;
	}
	
	@Override
	public List<String> getEmptyPropertyNames() {
		List<String> result = new ArrayList<String>();
		
		if (isFieldEmpty(getElement().getName()))
			result.add("name");
		if (getElement().getCompositions().isEmpty())
			result.add("compositions");
		
		return result;
	}
	
	@Override
	public void setElementFromRequest(HttpServletRequest request) {
		SEISaudeDefaultFacade<FoodComponent,Long> foodComponentFacade = SEISaudeDefaultFacade.getInstance(FoodComponent.class);
		Set<FoodComponent> foodComponentList = new HashSet<FoodComponent>();
		String sizeParam = request.getParameter("foodComponentsListSize");
		for (int i = 0; i < Integer.parseInt(sizeParam == null ? "0" : sizeParam); i++) {
			String eachComponentNameValue = request.getParameter("componentName" + String.valueOf(i));
			String eachComponentPercentageValue = request.getParameter("componentPergentage" + String.valueOf(i));
			if (!eachComponentNameValue.isEmpty() && !eachComponentPercentageValue.isEmpty()) {
				FoodComponent theComponent = new FoodComponent(eachComponentNameValue,Float.parseFloat(eachComponentPercentageValue));
				List<FoodComponent> matchingComponents = foodComponentFacade.getElementsByExample(theComponent,new ArrayList<String>());
				if (matchingComponents.isEmpty()) {
					foodComponentFacade.registerElement(theComponent);
				} else {
					theComponent = matchingComponents.get(0);
				}
				foodComponentList.add(theComponent);
			}
		}
		getElement().setCompositions(foodComponentList);
	}
}
